<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商家中心 - 新增商品</title>
    <!-- 外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        gray: {
                            100: '#F2F3F5',
                            200: '#E5E6EB',
                            300: '#C9CDD4',
                            400: '#86909C',
                            500: '#4E5969',
                            600: '#272E3B',
                            700: '#1D2129',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto { content-visibility: auto; }
            .btn-primary { @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-success { @apply bg-success hover:bg-success/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-warning { @apply bg-warning hover:bg-warning/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-danger { @apply bg-danger hover:bg-danger/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .btn-outline { @apply border border-gray-300 hover:border-primary text-gray-600 hover:text-primary font-medium py-2 px-4 rounded-lg transition-all duration-200; }
            .form-label { @apply block text-sm font-medium text-gray-700 mb-1; }
            .form-input { @apply w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all; }
            .form-select { @apply w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none transition-all appearance-none bg-white; }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
<!-- 顶部导航（与仪表盘一致） -->
<header class="sticky top-0 z-50 bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center">
            <i class="fa fa-briefcase text-primary text-2xl mr-2"></i>
            <h1 class="text-xl font-bold text-gray-700">商家管理中心</h1>
        </div>
        <div class="flex items-center gap-4">
            <div class="relative">
                <button class="flex items-center text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-lg"></i>
                    <span class="absolute -top-1 -right-1 bg-danger text-white text-xs w-4 h-4 rounded-full flex items-center justify-center">3</span>
                </button>
            </div>
            <div class="flex items-center gap-2">
                <img src="https://picsum.photos/200/200" alt="商家头像" class="w-8 h-8 rounded-full object-cover">
                <span class="text-gray-600">shopEasy店</span>
                <i class="fa fa-angle-down text-gray-400"></i>
            </div>
            <a href="../index.html"><button class="text-gray-600 hover:text-danger transition-colors" onclick="util.logout()">
                <i class="fa fa-sign-out"></i>
                <span class="ml-1">退出登录</span>
            </button></a>
        </div>
    </div>
</header>

<!-- 主体内容：侧边栏 + 主内容区 -->
<div class="flex-grow flex">
    <!-- 侧边栏导航（与仪表盘一致） -->
    <aside class="w-64 bg-white shadow-sm h-[calc(100vh-64px)] sticky top-16">
        <nav class="py-4">
            <div class="px-4 py-2 text-xs font-medium text-gray-400">核心功能</div>
            <a href="dashboard.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                <i class="fa fa-tachometer mr-3"></i>
                <span>仪表盘</span>
            </a>
            <a href="product-list.html" class="flex items-center px-4 py-3 text-primary bg-primary/5 border-l-4 border-primary">
                <i class="fa fa-cubes mr-3"></i>
                <span>商品管理</span>
            </a>
            <a href="order-list.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                <i class="fa fa-list-alt mr-3"></i>
                <span>订单管理</span>
            </a>
            <div class="px-4 py-2 mt-4 text-xs font-medium text-gray-400">店铺设置</div>
            <a href="shop-setting.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                <i class="fa fa-cog mr-3"></i>
                <span>店铺设置</span>
            </a>
            <a href="account-setting.html" class="flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-colors">
                <i class="fa fa-user mr-3"></i>
                <span>账号设置</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-grow p-6">
        <!-- 页面标题与面包屑 -->
        <div class="mb-6">
            <div class="flex items-center gap-2 text-sm text-gray-500 mb-2">
                <a href="dashboard.html" class="hover:text-primary transition-colors">仪表盘</a>
                <i class="fa fa-angle-right text-xs"></i>
                <a href="product-list.html" class="hover:text-primary transition-colors">商品管理</a>
                <i class="fa fa-angle-right text-xs"></i>
                <span class="text-gray-700">新增商品</span>
            </div>
            <h2 class="text-xl font-bold text-gray-700">新增商品</h2>
            <p class="text-gray-400 mt-1">填写商品信息，完成后提交上架</p>
        </div>

        <!-- 商品表单 -->
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <form id="productForm" class="space-y-6">
                <!-- 基础信息 -->
                <div class="border-b border-gray-200 pb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">基础信息</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- 商品名称 -->
                        <div>
                            <label class="form-label" for="productName">商品名称 <span class="text-danger">*</span></label>
                            <input
                                    type="text"
                                    id="productName"
                                    name="name"
                                    class="form-input"
                                    placeholder="请输入商品名称（不超过200字符）"
                                    required
                            >
                            <p class="mt-1 text-xs text-gray-500">建议包含核心卖点，如：2024新款夏季短袖T恤男纯棉宽松透气上衣</p>
                        </div>
                        <!-- 商品类目 -->
                        <div>
                            <label class="form-label" for="productCategory">商品类目 <span class="text-danger">*</span></label>
                            <div class="relative">
                                <select id="productCategory" name="category" class="form-select" required>
                                    <option value="">请选择类目</option>
                                    <!-- 电子产品大类 -->
                                    <option value="电子产品">电子产品</option>
                                    <option value="电子产品 - 手机">电子产品 - 手机</option>
                                    <option value="电子产品 - 电脑">电子产品 - 电脑</option>
                                    <option value="电子产品 - 音频设备">电子产品 - 音频设备</option>
                                    <option value="电子产品 - 相机">电子产品 - 相机</option>
                                    <option value="电子产品 - 家用电器">电子产品 - 家用电器</option>

                                    <!-- 服装鞋帽大类 -->
                                    <option value="服装鞋帽">服装鞋帽</option>
                                    <option value="服装鞋帽 - 男装">服装鞋帽 - 男装</option>
                                    <option value="服装鞋帽 - 女装">服装鞋帽 - 女装</option>
                                    <option value="服装鞋帽 - 童装">服装鞋帽 - 童装</option>
                                    <option value="服装鞋帽 - 鞋类">服装鞋帽 - 鞋类</option>
                                    <option value="服装鞋帽 - 配饰">服装鞋帽 - 配饰</option>

                                    <!-- 家居用品大类 -->
                                    <option value="家居用品">家居用品</option>
                                    <option value="家居用品 - 家具">家居用品 - 家具</option>
                                    <option value="家居用品 - 装饰">家居用品 - 装饰</option>
                                    <option value="家居用品 - 厨房用品">家居用品 - 厨房用品</option>
                                    <option value="家居用品 - 床上用品">家居用品 - 床上用品</option>

                                    <!-- 食品生鲜大类 -->
                                    <option value="食品生鲜">食品生鲜</option>
                                    <option value="食品生鲜 - 生鲜蔬果">食品生鲜 - 生鲜蔬果</option>
                                    <option value="食品生鲜 - 休闲零食">食品生鲜 - 休闲零食</option>
                                    <option value="食品生鲜 - 饮料">食品生鲜 - 饮料</option>
                                    <option value="食品生鲜 - 粮油米面">食品生鲜 - 粮油米面</option>

                                    <!-- 美妆护肤大类 -->
                                    <option value="美妆护肤">美妆护肤</option>
                                    <option value="美妆护肤 - 护肤品">美妆护肤 - 护肤品</option>
                                    <option value="美妆护肤 - 彩妆">美妆护肤 - 彩妆</option>
                                    <option value="美妆护肤 - 美发产品">美妆护肤 - 美发产品</option>
                                    <option value="美妆护肤 - 个人护理">美妆护肤 - 个人护理</option>

                                    <!-- 新增其他大类 -->
                                    <option value="图书音像">图书音像</option>
                                    <option value="玩具乐器">玩具乐器</option>
                                    <option value="运动户外">运动户外</option>
                                    <option value="汽车用品">汽车用品</option>
                                    <option value="珠宝首饰">珠宝首饰</option>

                                </select>
                                <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 pointer-events-none">
            <i class="fa fa-angle-down"></i>
        </span>
                            </div>
                        </div>
                        <!-- 商品品牌 -->
                        <div>
                            <label class="form-label" for="productBrand">商品品牌 <span class="text-danger">*</span></label>
                            <input
                                    type="text"
                                    id="productBrand"
                                    name="brand"
                                    class="form-input"
                                    placeholder="请输入商品品牌名称"
                                    required
                            >
                            <p class="mt-1 text-xs text-gray-500">请输入正确的品牌名称，如：华为、苹果、耐克等</p>
                        </div>
                        <!-- 商品规格 -->
                        <div>
                            <label class="form-label" for="productSpec">商品规格 <span class="text-danger">*</span></label>
                            <input
                                    type="text"
                                    id="productSpec"
                                    name="spec"
                                    class="form-input"
                                    placeholder="请按「颜色/尺码」格式输入，如：蓝色/29、白色/S"
                            required
                            >
                            <p class="mt-1 text-xs text-gray-500">
                                必须按「颜色/尺码」格式输入，多个规格用逗号分隔（如：蓝色/29,黑色/30,白色/S）
                            </p>
                        </div>
                    </div>
                </div>

                <!-- 价格与库存 -->
                <div class="border-b border-gray-200 pb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">价格与库存</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <!-- 商品价格（分） -->
                        <div>
                            <label class="form-label" for="productPrice">商品价格（元） <span class="text-danger">*</span></label>
                            <div class="relative">

                                <input
                                        type="number"
                                        id="productPrice"
                                        name="price"
                                        class="form-input pl-8"
                                        placeholder="￥请输入商品价格"
                                        step="0.01"
                                        min="0"
                                        required
                                >
                            </div>
                            <p class="mt-1 text-xs text-gray-500">系统将自动转换为分存储（如输入99.00，实际存储9900）</p>
                        </div>
                        <!-- 商品库存 -->
                        <div>
                            <label class="form-label" for="productStock">商品库存 <span class="text-danger">*</span></label>
                            <div class="relative flex items-center">
                                <!-- 图标移到输入框外部 -->
                                <span class="text-gray-500 mr-2">
            <i class="fa fa-cubes"></i>
        </span>
                                <input
                                        type="number"
                                        id="productStock"
                                        name="stock"
                                        class="form-input"
                                        placeholder="请输入商品库存数量"
                                        min="0"
                                        required
                                >
                            </div>
                        </div>
                        <!-- 商品状态 -->
                        <div>
                            <label class="form-label" for="productStatus">商品状态 <span class="text-danger">*</span></label>
                            <div class="relative">
                                <select id="productStatus" name="status" class="form-select" required>
                                    <option value="1">正常（上架）</option>
                                    <option value="2">下架</option>
                                </select>
                                <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 pointer-events-none">
                                        <i class="fa fa-angle-down"></i>
                                    </span>
                            </div>
                            <p class="mt-1 text-xs text-gray-500">选择“正常”将直接上架商品，“下架”商品仅自己可见</p>
                        </div>
                    </div>
                </div>

                <!-- 商品图片 -->
                <div class="border-b border-gray-200 pb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">商品图片</h3>
                    <div>
                        <label class="form-label">主图上传 <span class="text-danger">*</span></label>
                        <div class="mt-2 flex items-center gap-4">
                            <div id="mainImagePreview" class="w-32 h-32 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center bg-gray-50">
                                <div class="text-center">
                                    <i class="fa fa-image text-gray-400 text-2xl mb-2"></i>
                                    <p class="text-xs text-gray-500">点击上传图片</p>
                                </div>
                            </div>
                            <div class="flex-1">
                                <p class="text-sm text-gray-500 mb-2">支持JPG、PNG格式，建议尺寸800x800px，大小不超过2MB</p>
                                <label class="btn-outline inline-flex items-center cursor-pointer">
                                    <i class="fa fa-upload mr-1"></i>
                                    <span>选择图片</span>
                                    <input type="file" name="image" accept="image/jpeg,image/png" class="hidden" onchange="previewMainImage(this)">
                                </label>
                            </div>
                        </div>
                        <input type="hidden" name="imageUrl" id="imageUrl">
                    </div>
                </div>

                <!-- 推广设置 -->
                <div>
                    <h3 class="text-lg font-medium text-gray-700 mb-4">推广设置</h3>
                    <div class="flex items-center">
                        <input
                                type="checkbox"
                                id="isAD"
                                name="isAD"
                                class="h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary/30"
                        >
                        <label for="isAD" class="ml-2 text-sm text-gray-700">设置为推广商品</label>
                    </div>
                    <p class="mt-2 text-sm text-gray-500">推广商品将在平台首页、分类页等位置优先展示（需额外支付推广费用）</p>
                </div>

                <!-- 表单操作按钮 -->
                <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                    <a href="product-list.html" class="btn-outline">
                        <i class="fa fa-arrow-left mr-1"></i>
                        <span>返回列表</span>
                    </a>
                    <button type="submit" class="btn-primary">
                        <i class="fa fa-save mr-1"></i>
                        <span>提交保存</span>
                    </button>
                </div>
            </form>
        </div>
    </main>
</div>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 py-4 text-center text-sm text-gray-500">
    © 2025 ShopEasy 电商平台 - 商家管理系统，保留所有权利。
</footer>
<script src="../js/vue.js"></script>
<script src="../js/axios.min.js"></script>
<script src="../js/common.js"></script>
<script>
    // 存储选中的图片文件
    let productImageFile = null;

    // 图片预览功能
    function previewMainImage(input) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            productImageFile = file;

            // 验证文件格式和大小
            const allowedTypes = ['image/jpeg', 'image/png'];
            if (!allowedTypes.includes(file.type)) {
                alert('请上传JPG或PNG格式的图片');
                productImageFile = null;
                input.value = '';
                return;
            }
            if (file.size > 5 * 1024 * 1024) { // 限制5MB内
                alert('图片大小不能超过5MB');
                productImageFile = null;
                input.value = '';
                return;
            }

            // 本地预览
            const reader = new FileReader();
            reader.onload = function(e) {
                const previewContainer = document.getElementById('mainImagePreview');
                previewContainer.innerHTML = `<img src="${e.target.result}" alt="商品主图预览" class="w-full h-full object-cover rounded-lg">`;
            }
            reader.readAsDataURL(file);
        }
    }

    // 表单提交逻辑
    document.addEventListener('DOMContentLoaded', function() {
        const productForm = document.getElementById('productForm');
        productForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // 表单验证
            if (!productImageFile) {
                alert('请先上传商品主图');
                return;
            }

            const name = document.getElementById('productName').value.trim();
            const price = document.getElementById('productPrice').value;
            const stock = document.getElementById('productStock').value;
            const category = document.getElementById('productCategory').value;
            const brand = document.getElementById('productBrand').value;

            if (!name) { alert('请输入商品名称'); return; }
            if (!price || isNaN(parseFloat(price)) || parseFloat(price) < 0) { alert('请输入有效价格'); return; }
            if (!stock || isNaN(parseInt(stock)) || parseInt(stock) < 0) { alert('请输入有效库存'); return; }
            if (!category) { alert('请选择商品类目'); return; }
            if (!brand) { alert('请输入商品品牌'); return; }

// ------------ 核心：手动构造带空格的JSON格式 ------------
            const specInput = document.getElementById('productSpec').value.trim();
            let specJson = ''; // 最终传给后端的JSON字符串（带空格）

            if (specInput) {
                // 1. 按逗号分割多个规格（如“蓝色/29,黑色/30” → 拆分为两个规格）
                const specList = specInput.split(',').map(item => item.trim()); // 去除每个规格的前后空格
                const formattedSpecArr = [];

                // 2. 遍历每个规格，手动拼接单个规格的JSON字符串
                for (const spec of specList) {
                    // 按“/”分割颜色和尺码（如“蓝色/29” → ["蓝色", "29"]）
                    const [color, size] = spec.split('/').map(item => item.trim());

                    // 校验格式：必须包含颜色和尺码，否则提示错误
                    if (!color || !size) {
                        alert(`规格“${spec}”格式错误，请按「颜色/尺码」输入（如：蓝色/29）`);
                        return; // 终止提交，直到格式正确
                    }

                    // 3. 手动拼接单个规格的JSON（严格控制空格：键值双引号、逗号后空格）
                    const singleSpecJson = `{"颜色": "${color}", "尺码": "${size}"}`;
                    formattedSpecArr.push(singleSpecJson);
                }

                // 4. 处理多规格/单规格场景，拼接最终JSON
                if (formattedSpecArr.length === 1) {
                    // 单规格：直接取单个JSON字符串（如 {"颜色": "蓝色", "尺码": "29"}）
                    specJson = formattedSpecArr[0];
                } else {
                    // 多规格：拼接为数组格式（如 [{"颜色": "蓝色", "尺码": "29"}, {"颜色": "黑色", "尺码": "30"}]）
                    specJson = `[${formattedSpecArr.join(', ')}]`; // 数组内用“逗号+空格”分隔
                }
            }

            // 构造FormData（与后端Item2DTO字段完全对应）
            const formData = new FormData();
            formData.append('name', name);
            formData.append('price', Math.round(parseFloat(price) * 100)); // 转换为分
            formData.append('stock', parseInt(stock));
            formData.append('image', productImageFile); // 明确指定文件名
            formData.append('category', category);
            formData.append('brand', brand);
            formData.append('spec', specJson);
            formData.append('isAD', document.getElementById('isAD').checked ? 'true' : 'false'); // 确保布尔值正确传递
            formData.append('status', parseInt(document.getElementById('productStatus').value));

            try {
                // 打印FormData内容用于调试
                console.log('FormData内容:');
                for (let pair of formData.entries()) {
                    console.log(pair[0] + ': ' + (pair[0] === 'image' ? 'File(' + pair[1].name + ')' : pair[1]));
                }

                // 关键修复：移除手动设置的Content-Type，让浏览器自动处理
                const response = await axios.post('/items/add', formData, {
                    headers: {
                        // 不要设置Content-Type，删除这一行
                        // 'Content-Type': 'multipart/form-data',
                    },
                    timeout: 30000
                });

                alert('商品新增成功！');
                window.location.href = 'product-list.html';
            } catch (error) {
                console.error('请求错误详情:', {
                    status: error.response?.status,
                    statusText: error.response?.statusText,
                    headers: error.response?.headers,
                    data: error.response?.data
                });

                if (error.response?.status === 415) {
                    alert('提交失败: 服务器不支持当前请求格式，请检查后端配置');
                } else if (error.response) {
                    alert(`提交失败: ${error.response.data.msg || '服务器处理错误'}`);
                } else if (error.request) {
                    alert('请求失败: 网络异常，请检查连接');
                } else {
                    alert(`请求失败: ${error.message}`);
                }
            }
        });
    });
</script>

